package com.sinosoft.taxbenefit.core.securityguard.biz.service.impl;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.ws.BindingProvider;
import javax.xml.ws.Holder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.sinosoft.platform.base.TaxBaseService;
import com.sinosoft.platform.common.util.DateUtil;
import com.sinosoft.platform.common.util.StringUtil;
import com.sinosoft.taxbenefit.api.base.HXResultCodeDTO;
import com.sinosoft.taxbenefit.api.config.ENUM_BZ_RESPONSE_RESULT;
import com.sinosoft.taxbenefit.api.config.ENUM_DISPOSE_TYPE;
import com.sinosoft.taxbenefit.api.config.ENUM_SENDSERVICE_CODE;
import com.sinosoft.taxbenefit.api.dto.request.TaxFaulTaskDTO;
import com.sinosoft.taxbenefit.api.dto.request.base.CoreRequestHead;
import com.sinosoft.taxbenefit.api.dto.request.base.ParamHeadDTO;
import com.sinosoft.taxbenefit.api.dto.request.base.ThirdSendResponseDTO;
import com.sinosoft.taxbenefit.api.dto.request.securityguard.ReqEndorsementCancelBodyDTO;
import com.sinosoft.taxbenefit.api.dto.request.securityguard.ReqEndorsementCancelInfoDTO;
import com.sinosoft.taxbenefit.api.dto.response.securityguard.ResultCancelEndorsement;
import com.sinosoft.taxbenefit.core.common.biz.service.CommonCodeService;
import com.sinosoft.taxbenefit.core.common.config.ENUM_BUSINESS_RESULR;
import com.sinosoft.taxbenefit.core.common.config.ENUM_RESULT_CODE;
import com.sinosoft.taxbenefit.core.common.config.ENUM_EBAO_SERVICE_PORT_CODE;
import com.sinosoft.taxbenefit.core.common.dto.EbaoServerPortDTO;
import com.sinosoft.taxbenefit.core.common.dto.ReqBusinessDTO;
import com.sinosoft.taxbenefit.core.common.dto.ReqBusinessDetailDTO;
import com.sinosoft.taxbenefit.core.common.dto.SendLogDTO;
import com.sinosoft.taxbenefit.core.common.dto.ThirdSendDTO;
import com.sinosoft.taxbenefit.core.ebaowebservice.EndorsementCancelService;
import com.sinosoft.taxbenefit.core.ebaowebservice.EndorsementCancelService_Service;
import com.sinosoft.taxbenefit.core.ebaowebservice.ResponseBody;
import com.sinosoft.taxbenefit.core.ebaowebservice.ResponseHeader;
import com.sinosoft.taxbenefit.core.ebaowebservice.ResponseJSON;
import com.sinosoft.taxbenefit.core.faultTask.biz.service.FaultTaskService;
import com.sinosoft.taxbenefit.core.generated.mapper.TaxContEndorsementMapper;
import com.sinosoft.taxbenefit.core.generated.mapper.TaxFaultTaskMapper;
import com.sinosoft.taxbenefit.core.generated.model.TaxContEndorsement;
import com.sinosoft.taxbenefit.core.generated.model.TaxContEndorsementExample;
import com.sinosoft.taxbenefit.core.generated.model.TaxFaultTask;
import com.sinosoft.taxbenefit.core.securityguard.biz.service.PreservationOfCancelService;
import com.sinosoft.taxbenefit.core.securityguard.dto.EndorsementCancelDTO;
import com.sinosoft.taxbenefit.core.securityguard.dto.EndorsementCancelInfoDTO;
import com.sinosoft.taxbenefit.core.securityguard.dto.EndorsementCancelResultBodyDTO;
import com.sinosoft.taxbenefit.core.securityguard.dto.EndorsementCancelResultDTO;

@Service
public class PreservationOfCancelServiceImpl extends TaxBaseService implements PreservationOfCancelService {
	@Autowired
	CommonCodeService commonCodeService;
	@Autowired
	private FaultTaskService faultTaskService;
	@Autowired
	TaxFaultTaskMapper  taxFaultTaskMapper;//异常任务
	@Autowired
	private TaxContEndorsementMapper taxContEndorsementMapper;// 保全变更记录
	@Override
	public ThirdSendResponseDTO modifyPreservationCancel(ReqEndorsementCancelInfoDTO reqbodyDTO, ParamHeadDTO paramHead) {
		ThirdSendResponseDTO thirdSendResponse = new ThirdSendResponseDTO();
		try {
			List<ReqBusinessDetailDTO> reqBusinessDetailList = new ArrayList<ReqBusinessDetailDTO>();
			ReqBusinessDTO businessDTO = commonCodeService.initReqBusinessDTO();
			logger.info("保全撤销上传（核心请求）JSON 体数据内容："+ JSONObject.toJSONString(reqbodyDTO));
			// 1.转换为中保信dto
			EndorsementCancelInfoDTO cancel = this.changeDTO(reqbodyDTO);
			EndorsementCancelDTO body = new EndorsementCancelDTO();
			body.setEndorsementCancel(cancel);
			ThirdSendDTO thirdSendDTO = commonCodeService.createThirdSend( ENUM_EBAO_SERVICE_PORT_CODE.SERCURITY_CANCEL.code(),paramHead, body);
			logger.info("保全撤销上传（请求中保信）JSON 体数据内容："+ JSONObject.toJSONString(thirdSendDTO));
			Holder<ResponseHeader> responseHeaderHolder = new Holder<ResponseHeader>();
			Holder<ResponseBody> responseBodyHolder = new Holder<ResponseBody>();
			EbaoServerPortDTO ebaoServerPort = commonCodeService.queryEBaoServerInfoByPortCode(ENUM_EBAO_SERVICE_PORT_CODE.SERCURITY_CANCEL.code());
			String portUrl = ebaoServerPort.getPortUrl();
			URL wsdlLocation = new URL(portUrl);
			EndorsementCancelService_Service service = new EndorsementCancelService_Service(wsdlLocation);
			EndorsementCancelService servicePort = service.getEndorsementCancelServicePort();
			BindingProvider bp = (BindingProvider) servicePort;
			bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, portUrl);
			servicePort.endorsementCancel(thirdSendDTO.getHead(), thirdSendDTO.getBody(), responseHeaderHolder,responseBodyHolder);
			ResponseHeader responseHeader = responseHeaderHolder.value;
			ResponseBody responseBody = responseBodyHolder.value;
			logger.info("保全撤销上传(中报信返回)JSON数据内容：" + responseBody.getJsonString());
			ResponseJSON responseJSON = new ResponseJSON();
			responseJSON.setResponseBody(responseBody);
			responseJSON.setResponseHeader(responseHeader);
			// 封装发送报文日志对象
			SendLogDTO sendLog = new SendLogDTO();
			sendLog.setSerialNo(paramHead.getSerialNo());
			sendLog.setPortCode(ENUM_EBAO_SERVICE_PORT_CODE.SERCURITY_CANCEL.code());
			sendLog.setRequestContent(JSONObject.toJSONString(thirdSendDTO));
			sendLog.setResponseContent(JSONObject.toJSONString(responseJSON));
			sendLog.setTargetCode(ENUM_SENDSERVICE_CODE.EBAO.code());
			sendLog.setState(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
			sendLog.setDescription(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
			commonCodeService.addLogSend(sendLog);
			// 3.封装返回核心dto;
			if (ENUM_RESULT_CODE.SUCCESS.code().equals(responseHeader.getResultCode())
					|| ENUM_RESULT_CODE.INPUT_LOCALITY_SUCCESS.code().equals(responseHeader.getResultCode())) {
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
				thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
				// 持久化
				this.modifyEndorsementCancelState(reqbodyDTO);
			}else{
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
				List list = responseHeader.getResultMessage().getMessage();
				if(list != null && list.size() > 0){
					StringBuffer sbStr = new StringBuffer(); 
					for(String mess : responseHeader.getResultMessage().getMessage()){
						sbStr.append(mess).append("|");
					}
					String message = sbStr.substring(0, sbStr.length()-1).toString();
					thirdSendResponse.setResultDesc(message);
				}else{
					thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.FAIL.description());
				}
			}
			if (!StringUtil.isEmpty(responseBody.getJsonString())) {
				EndorsementCancelResultDTO policy = JSONObject.parseObject( responseBody.getJsonString(),EndorsementCancelResultDTO.class);
				// 成功记录数
				Integer successNum = 0;
				// 失败记录数
				Integer failNum = 0;
				EndorsementCancelResultBodyDTO resPolicy = policy.getEndorsementCancelResult();
				ResultCancelEndorsement endorsement = new ResultCancelEndorsement();
				HXResultCodeDTO resultinfo = new HXResultCodeDTO();
				StringBuffer sb = new StringBuffer();
				String message = "";
				if (resPolicy.getResult().getResultMessage() != null) {
					for (String s : resPolicy.getResult().getResultMessage()) {
						sb.append(s).append("|");
					}
					message = sb.substring(0, sb.length() - 1).toString();
				}
				resultinfo.setResultCode(resPolicy.getResult().getResultCode());
				resultinfo.setResultMessage(message);
				endorsement.setResult(resultinfo);
				thirdSendResponse.setResJson(endorsement);
				// 成功记录计数
				if (ENUM_RESULT_CODE.SUCCESS.code().equals( resPolicy.getResult().getResultCode())) {
					successNum += 1;
				} else {
					// 失败记录计数
					failNum += 1;
					// 记录失败明细
					ReqBusinessDetailDTO reqBusinessDetailDTO = commonCodeService.initReqBusinessDetailDTO(paramHead);
					reqBusinessDetailDTO.setResultCode(ENUM_BUSINESS_RESULR.FAIL.code());
					reqBusinessDetailDTO.setResultMessage(message);
					reqBusinessDetailList.add(reqBusinessDetailDTO);
				}
				// 登记请求记录
				businessDTO.setReqSuccessNum(successNum);
				businessDTO.setReqFailNum(failNum);
			} else {
				businessDTO.setReqFailNum(responseHeader.getRecordNum());
				// 记录失败明细
				businessDTO.setReqFailNum(responseHeader.getRecordNum());
				ReqBusinessDetailDTO reqBusinessDetailDTO = commonCodeService.initReqBusinessDetailDTO(paramHead);
				reqBusinessDetailDTO.setResultCode(ENUM_BUSINESS_RESULR.FAIL.code());
				reqBusinessDetailDTO.setResultMessage(thirdSendResponse.getResultDesc());
				reqBusinessDetailList.add(reqBusinessDetailDTO);
			}
			// 添加记录失败明细
			commonCodeService.addReqBusinessDetail(reqBusinessDetailList);
			// 添加请求交易记录数
			businessDTO.setRequetNum(responseHeader.getRecordNum());
			commonCodeService.addReqBusinessCollate(businessDTO);
		} catch (MalformedURLException e) {
			e.printStackTrace();
			thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.code());
			thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.description());
			TaxFaulTaskDTO taxFaultTask = new TaxFaulTaskDTO();
			taxFaultTask.setServerPortCode(paramHead.getPortCode());
			taxFaultTask.setServerPortName(paramHead.getPortName());
			taxFaultTask.setAreaCode(paramHead.getAreaCode());
			taxFaultTask.setSerialNo(paramHead.getSerialNo());
			taxFaultTask.setDisposeType(ENUM_DISPOSE_TYPE.ERROR.code());
			faultTaskService.addTaxFaultTask(taxFaultTask);
			logger.error("保全撤销上传后置处理失败：" + e.getMessage());
		}
		return thirdSendResponse;
	}
	/**
	 * 保全撤销转中保信对象
	 * @param reqbodyDTO
	 * @return
	 */
	private EndorsementCancelInfoDTO changeDTO( ReqEndorsementCancelInfoDTO reqbodyDTO) {
		EndorsementCancelInfoDTO cancel = new EndorsementCancelInfoDTO();
		cancel.setPolicyNo(reqbodyDTO.getPolicyNo());
		cancel.setEndorsementNo(reqbodyDTO.getEndorsementNo());
		return cancel;
	}
	/**
	 * 修改保全记录
	 */
	private void modifyPreservationOfChange(TaxContEndorsement endor) {
		taxContEndorsementMapper.updateByPrimaryKeySelective(endor);
	}
	/**
	 * 查找保全信息
	 * 
	 * @param policyNo
	 * @return
	 */
	private TaxContEndorsement queryPreservationOfChangeByPolicyNo( String policyNo, String endorNo) {
		TaxContEndorsementExample example = new TaxContEndorsementExample();
		example.createCriteria().andContNoEqualTo(policyNo).andEdorNoEqualTo(endorNo);
		List<TaxContEndorsement> endorlist = taxContEndorsementMapper.selectByExample(example);
		if (endorlist != null && endorlist.size() > 0) {
			return endorlist.get(0);
		}
		return null;
	}
	/**
	 * 保全撤销上传异常接口
	 */
	@Override
	public ThirdSendResponseDTO modifyCancelExceptionJob(String reqJSON, String portCode, TaxFaultTask faultTask) {
		ThirdSendResponseDTO thirdSendResponse = new ThirdSendResponseDTO();
		try {
			List<ReqBusinessDetailDTO> reqBusinessDetailList = new ArrayList<ReqBusinessDetailDTO>();
			ReqBusinessDTO businessDTO = commonCodeService.initReqBusinessDTO();
			ParamHeadDTO paramHeadDTO = new ParamHeadDTO();
			CoreRequestHead coreRequestHead = new CoreRequestHead();
			ReqEndorsementCancelBodyDTO reqObject = JSONObject.parseObject(reqJSON, ReqEndorsementCancelBodyDTO.class);
			ReqEndorsementCancelInfoDTO reqbodyDTO = (ReqEndorsementCancelInfoDTO) reqObject.getBody();
			coreRequestHead = reqObject.getRequestHead();
			paramHeadDTO.setPortCode(portCode);
			paramHeadDTO.setAreaCode(coreRequestHead.getAreaCode());
			paramHeadDTO.setRecordNum(coreRequestHead.getRecordNum());
			paramHeadDTO.setSerialNo(coreRequestHead.getSerialNo());
			logger.info("保全撤销上传异常接口（核心请求）JSON 体数据内容："+ JSONObject.toJSONString(reqbodyDTO));
			// 1.转换为中保信dto
			EndorsementCancelInfoDTO cancel = this.changeDTO(reqbodyDTO);
			EndorsementCancelDTO body = new EndorsementCancelDTO();
			body.setEndorsementCancel(cancel);

			ThirdSendDTO thirdSendDTO = commonCodeService.createThirdSend(ENUM_EBAO_SERVICE_PORT_CODE.SERCURITY_CANCEL.code(), paramHeadDTO, body);
			logger.info("保全撤销上传异常接口（请求中保信）JSON 体数据内容："+ JSONObject.toJSONString(thirdSendDTO));
			Holder<ResponseHeader> responseHeaderHolder = new Holder<ResponseHeader>();
			Holder<ResponseBody> responseBodyHolder = new Holder<ResponseBody>();
			EbaoServerPortDTO ebaoServerPort = commonCodeService.queryEBaoServerInfoByPortCode(ENUM_EBAO_SERVICE_PORT_CODE.SERCURITY_CANCEL.code());
			String portUrl = ebaoServerPort.getPortUrl();
			URL wsdlLocation = new URL(portUrl);
			EndorsementCancelService_Service service = new EndorsementCancelService_Service(wsdlLocation);
			EndorsementCancelService servicePort = service.getEndorsementCancelServicePort();
			BindingProvider bp = (BindingProvider) servicePort;
			bp.getRequestContext().put(	BindingProvider.ENDPOINT_ADDRESS_PROPERTY, portUrl);
			servicePort.endorsementCancel(thirdSendDTO.getHead(), thirdSendDTO.getBody(), responseHeaderHolder, responseBodyHolder);
			ResponseHeader responseHeader = responseHeaderHolder.value;
			ResponseBody responseBody = responseBodyHolder.value;
			logger.info("保全撤销上传异常接口(中报信返回)JSON数据内容：" + responseBody.getJsonString());
			ResponseJSON responseJSON = new ResponseJSON();
			responseJSON.setResponseBody(responseBody);
			responseJSON.setResponseHeader(responseHeader);

			// 初始化头部错误信息
			String messageBody = ENUM_BZ_RESPONSE_RESULT.FAIL.description();
			// 3.封装返回核心dto;
			if (ENUM_RESULT_CODE.SUCCESS.code().equals( responseHeader.getResultCode())
					|| ENUM_RESULT_CODE.INPUT_LOCALITY_SUCCESS.code().equals(responseHeader.getResultCode())) {
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
				thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
				// 持久化
				modifyEndorsementCancelState(reqbodyDTO);
			}else{
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
				List list = responseHeader.getResultMessage().getMessage();
				if(list != null && list.size() > 0){
					StringBuffer sbStr = new StringBuffer(); 
					for(String mess : responseHeader.getResultMessage().getMessage()){
						sbStr.append(mess).append("|");
					}
					String message = sbStr.substring(0, sbStr.length()-1).toString();
					thirdSendResponse.setResultDesc(message);
				}else{
					thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.FAIL.description());
				}
				faultTask.setDisposeResult(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
			}
			if (!StringUtil.isEmpty(responseBody.getJsonString())) {
				EndorsementCancelResultDTO policy = JSONObject.parseObject( responseBody.getJsonString(),EndorsementCancelResultDTO.class);
				// 成功记录数
				Integer successNum = 0;
				// 失败记录数
				Integer failNum = 0;
				EndorsementCancelResultBodyDTO resPolicy = policy.getEndorsementCancelResult();
				ResultCancelEndorsement endorsement = new ResultCancelEndorsement();
				HXResultCodeDTO resultinfo = new HXResultCodeDTO();
				StringBuffer sb = new StringBuffer();
				String message = "";
				if (resPolicy.getResult().getResultMessage() != null) {
					for (String s : resPolicy.getResult().getResultMessage()) {
						sb.append(s).append("|");
					}
					message = sb.substring(0, sb.length() - 1).toString();
				}
				resultinfo.setResultCode(resPolicy.getResult().getResultCode());
				resultinfo.setResultMessage(message);
				endorsement.setResult(resultinfo);
				thirdSendResponse.setResJson(endorsement);
				// 成功记录计数
				if (ENUM_RESULT_CODE.SUCCESS.code().equals(resPolicy.getResult().getResultCode())) {
					successNum += 1;
				} else {
					// 失败记录计数
					failNum += 1;
					ReqBusinessDetailDTO reqBusinessDetailDTO = commonCodeService.initReqBusinessDetailDTO(paramHeadDTO);
					reqBusinessDetailDTO.setResultCode(ENUM_BUSINESS_RESULR.FAIL.code());
					reqBusinessDetailDTO.setResultMessage(message);
					reqBusinessDetailList.add(reqBusinessDetailDTO);
				}
				// 登记请求记录
				businessDTO.setReqSuccessNum(successNum);
				businessDTO.setReqFailNum(failNum);
			} else {
				thirdSendResponse.setResJson(messageBody);
				businessDTO.setReqFailNum(responseHeader.getRecordNum());
				// 记录失败明细
				businessDTO.setReqFailNum(responseHeader.getRecordNum());
				ReqBusinessDetailDTO reqBusinessDetailDTO = commonCodeService.initReqBusinessDetailDTO(paramHeadDTO);
				reqBusinessDetailDTO.setResultCode(ENUM_BUSINESS_RESULR.FAIL.code());
				reqBusinessDetailDTO.setResultMessage(thirdSendResponse.getResultDesc());
				reqBusinessDetailList.add(reqBusinessDetailDTO);
			}
			// 添加记录失败明细
			commonCodeService.addReqBusinessDetail(reqBusinessDetailList);
			// 添加请求交易记录数
			businessDTO.setRequetNum(responseHeader.getRecordNum());
			commonCodeService.addReqBusinessCollate(businessDTO);
			faultTask.setDisposeResult(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
		} catch (MalformedURLException e) {
			e.printStackTrace();
			logger.error("保全撤销上传异常接口后置处理失败：" + e.getMessage());
			thirdSendResponse.setResJson(e.getMessage());
			thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
			thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.FAIL.description());
			faultTask.setDisposeType(ENUM_DISPOSE_TYPE.ERROR.code());
			faultTask.setDisposeResult(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
		} finally{
			faultTask.setSuccessMessage(JSONObject.toJSONString(thirdSendResponse));
			faultTask.setDisposeDate(DateUtil.getCurrentDate());
			taxFaultTaskMapper.updateByPrimaryKeySelective(faultTask);
		}
		return thirdSendResponse;
	}

	/**
	 * 持久化
	 * @param reqbodyDTO
	 */
	private void modifyEndorsementCancelState( ReqEndorsementCancelInfoDTO reqbodyDTO) {
		try {
			TaxContEndorsement endorsement = queryPreservationOfChangeByPolicyNo( reqbodyDTO.getPolicyNo(), reqbodyDTO.getEndorsementNo());
			if (endorsement != null) {
				endorsement.setEdorCancelDate(DateUtil.getCurrentDate());
				modifyPreservationOfChange(endorsement);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("保全撤销持久化失败" + e.getMessage());
		}
	}
}
